const _ = require("underscore");

//默认的分页数据配置
var defaultPageConfig = {
	size : 10, //每页的记录数量
	num : 1 //当前页码
};
/**
 * 封装一个简易字符串缓存
 * 主要为了方便字符串的拼接, 防止频繁拼接的内存浪费
 */
class StringBuffer {
	constructor(str) {
		this.__strings = [];
		if(_.isString(str)){
			this.__strings.push(str);
		}
	}

	/**
	 * 向缓存当中追加字符串
	 * @param str
	 */
	append(str) {
		this.__strings.push(str);
	}

	/**
	 * 将缓存数组中的字符串拼合
	 * @returns {string}
	 */
	toString(){
		return this.__strings.join("");
	}
}

class Page {
	constructor(config){
		var pageConfig = _.clone(defaultPageConfig);
		_.extendOwn(pageConfig, config);
		//将对象中的值都转化为整数(从请求参数中获取的可能是字符串)
		pageConfig = _.mapObject(pageConfig, function(val){
			return parseInt(val);
		});
		this.pageSize = pageConfig.size;
		this.pageNow = pageConfig.num;
		this.rowStart = (pageConfig.num - 1) * this.pageSize;
	}

	/**
	 * 获取总页数
	 * @returns {number}
	 */
	getPageCount(){
		//JS中的整数除法获得的结果可以是浮点数
		if(this.rowCount % this.pageSize) {
			//Math.floor的作用是向下取整
			return Math.floor(this.rowCount / this.pageSize) + 1;
		} else {
			return Math.floor(this.rowCount / this.pageSize);
		}
	}

	/**
	 * 设置记录的总数
	 * @param count 记录总数
	 */
	setCount(count){
		this.rowCount = count;
	}

	/**
	 * 在页面中创建分页的HTML代码
	 */
	createHtml(){
		var disable = null;
		var href = null;
		var title = null;
		//如果当前是第一页, 则上一页不可用
		if(this.pageNow===1) {
			disable =  `class="disabled"`;
			href = "javascript:void(0)";
			title = "已经是第一页";
		} else {
			disable = "";
			href = `?page[num]=${this.pageNow-1}`;
			title = "上一页";
		}
		const htmlBuffer = new StringBuffer(`<nav style="text-align:center;">
		<ul class="pagination">
			<li ${disable} title="${title}">
				<a href="${href}" aria-label="Previous">
				<span aria-hidden="true">&laquo;</span>
				</a>
			</li>
			`);
		//起始页码
		const numStart = (this.pageNow-2 <= 0) ? 1 : this.pageNow - 2 ;
		//总页数
		const pageCount = this.getPageCount();

		for(let index=numStart ; index<=pageCount && index<=this.pageNow+2 ; index++) {
			let active = (index === this.pageNow) ? `class="active"` : "";
			let numHref = (index === this.pageNow) ? "javascript:void(0)" : `?page[num]=${index}`;
			htmlBuffer.append(`<li ${active}><a href="${numHref}">${index}</a></li>`);
		}
		//如果当前是最后一页, 则下一页不可用
		if(this.pageNow===pageCount) {
			disable =  `class="disabled"`;
			href = "javascript:void(0)";
			title = "已经是最后一页";
		} else {
			disable = "";
			href = `?page[num]=${this.pageNow+1}`;
			title = "下一页";
		}
		htmlBuffer.append(`<li ${disable} title="${title}">
			<a href="${href}" aria-label="Next">
				<span aria-hidden="true">&raquo;</span>
			</a>
			</li>
		</ul>
		</nav>`);
		return htmlBuffer.toString();
	}
}

module.exports = Page;